var commonJs = {};

var $ = null;
var util = null;

layui.use(['jquery', 'util'], function () {
    $ = layui.$, util = layui.util;
});

//用于多图片、多文件上传自定义标签，上传成功后填充文件id到**_fileIds元素中
commonJs.fillFileId = function (elementId, fileId) {
    if ($("#" + elementId)) {
        var ids = $("#" + elementId).val() || '';
        if (ids != '') {
            var idArray = ids.split(",");
            idArray.push(fileId);
            $("#" + elementId).val(idArray.join(","));
        } else {
            $("#" + elementId).val(fileId);
        }
    }
};

//用于多图片、多文件上传自定义标签，删除成功后更新文件id到**_fileIds元素中
commonJs.deleteFile = function (elementId, fileId) {
    commonJs.openConfirm("确定要删除该文件吗？", function () {
        var url = ctx + "/manage/file/file/remove";
        var data = {'id': fileId};
        commonJs.openAjax(url, data, function (result) {
            if (result.code == 0) {
                commonJs.openMsg('success', result.msg, function () {
                    $("#upload-files-" + fileId).remove();
                    var fileIds = $("#" + elementId).val() || "";
                    if (fileIds != '') {
                        var fileIdsArr = fileIds.split(",");
                        for (var i = 0; i < fileIdsArr.length; i++) {
                            if (fileIdsArr[i] == fileId) {
                                fileIdsArr.splice(i, 1);
                                break;
                            }
                        }
                        $("#" + elementId).val(fileIdsArr.join(","));
                    }
                });
            } else {
                commonJs.openMsg('error', result.msg);
            }
        });
    });
};

//下载上传的文件
commonJs.downloadFileUrl = function (fileUrl, fileName) {
    fileUrl = fileUrl.replace("files", "");
    // 创建隐藏的可下载链接
    var aLink = document.createElement('a');
    var src = ctx + "/manage/file/file/downloadByUrl?fileName=" + fileUrl;
    aLink.download = src;
    aLink.style.display = 'none';
    aLink.href = src;
    document.body.appendChild(aLink);
    aLink.click();
    document.body.removeChild(aLink);
};

//下载一般的文件
commonJs.downloadFile = function (url) {
    url = url || '';
    if (url == '') {
        return;
    }
    var aLink = document.createElement('a');
    aLink.download = url;
    aLink.style.display = 'none';
    aLink.href = url;
    document.body.appendChild(aLink);
    aLink.click();
    document.body.removeChild(aLink);
};


//打开ajax请求(请求地址, 参数, 成功后回调的函数, 失败后回调的函数)
commonJs.openAjax = function (url, data, success, error, hasLoading, type, dataType) {
    // 支持layer form
    if (undefined != data && undefined != data.field) data = data.field;
    if (undefined == type || '' == type) type = "POST";
    if (undefined == dataType || '' == dataType) dataType = "json";
    if (typeof (data) == "string") data = JSON.parse(data);
    if (null == error) {
        error = function () {
            commonJs.openMsg("error", "网络繁忙，请稍候再尝试！", null);
            if (hasLoading) {
                commonJs.closeLoad();
            }
        }
    }
    if (null == hasLoading) hasLoading = true;
    if (hasLoading) {
        commonJs.openLoad();
    }
    $.ajax({
        url: url
        , data: data
        , type: type
        , dataType: dataType
        , timeout: 30 * 60 * 1000
        , success: function (result) {
            if (hasLoading) {
                commonJs.closeLoad();
            }
            success(result);
        }
        , error: error
    });
};

// 打开信息框(type=info,warning,error,success)，2秒后自动关闭
commonJs.openMsg = function (type, message, callback) {
    if (callback == null) {
        callback = function () {
        };
    }
    var params = {shade: 0.3, time: 2000};
    if (type == 'info' || type == 'warning') {
        params.icon = 0;
    } else if (type == 'success') {
        params.icon = 1;
    } else if (type == 'error') {
        params.icon = 2;
    } else if (type == 'confirm') {
        params.icon = 3;
    } else if (type == 'lock') {
        params.icon = 4;
    } else if (type == 'cry') {
        params.icon = 5;
        params.anim = 6;
        params.shade = 0;
    } else if (type == 'smile') {
        params.icon = 6;
    }
    layer.msg(message, params, callback);
};

// 打开加载框
var modComLoad = [];
commonJs.openLoad = function () {
    var index = layer.load(1, {shade: 0.3});
    modComLoad.push(index);
};

// 关闭加载框
commonJs.closeLoad = function () {
    try {
        if (modComLoad != null && modComLoad.length > 0) {
            layer.close(modComLoad.shift());
        }
    } catch (e) {
    }
};

// 打开页内窗口
// data.dialogArea: full,half,mini
commonJs.openDialog = function (title, url, data, btn, funCallback1, funCallback2, funCallback3) {
    data = data || {};
    btn = btn || [];
    funCallback1 = funCallback1 || function () {
    };
    funCallback2 = funCallback2 || function () {
    };
    funCallback3 = funCallback3 || function () {
    };

    var btnName = [];
    var skin = null;
    if (btn.length > 0) {
        $.each(btn, function (idx, item) {
            var arrTemp = item.split("&");
            btnName.push(arrTemp[0]);
        });
    } else {
        btnName = ["保存", "返回"];
    }
    if (data.btnHide != null && data.btnHide != '') btnName = false;
    if (data.dialogSkin != null && data.dialogSkin != '') skin = data.dialogSkin;

    data.dialogArea = data.dialogArea || "half";
    var arrArea = ['70%', '70%'];
    if (Array.isArray(data.dialogArea)) {
        arrArea = data.dialogArea;
    } else if (data.dialogArea == "mini") {
        arrArea = ['40%', '40%'];
    }

    var index = layer.open({
        type: 2,
        title: title,
        skin: skin,
        area: arrArea,
        fixed: false,
        content: url,
        btnAlign: 'c',
        btn: btnName,
        yes: function (index, layero) {
            funCallback1(index, layero);
        },
        btn2: function (index, layero) {
            funCallback2(index, layero);
        },
        success: function (layero, index) {
            funCallback3(index, layero)
        }
    });
    if (data.dialogArea == "full") layer.full(index);
};

// 打开确认窗口
commonJs.openConfirm = function (text, ok, cancel) {
    if (undefined == ok) {
        ok = function (index) {
            //layer.close(index);
        };
    }
    if (undefined == cancel) {
        cancel = function (index) {
            layer.close(index);
        };
    }
    layer.confirm(text, {icon: 3, title: '信息', closeBtn: 0, btnAlign: 'c'}, ok, cancel);
};

// 打开信息框（不自动关闭）
commonJs.openInfo = function (title, content, btn, funCallback1, funCallback2, funCallback3) {
    funCallback1 = funCallback1 || function () {
    };
    funCallback2 = funCallback2 || function () {
    };
    funCallback3 = funCallback3 || function () {
    };
    layer.open({
        title: title
        , type: 1
        , content: '<div style="padding: 20px;line-height: 24px;font-size: 14px;">' + content + '</div>'
        , btn: (btn != null && btn != '' ? btn : ['我知道了'])
        , btnAlign: 'c'
        , yes: function (index, layero) {
            funCallback1();
            layer.close(index);
        }
        , btn2: function (index, layero) {
            funCallback2();
            layer.close(index);
            return false;
        }
        , btn3: function (index, layero) {
            funCallback3();
            layer.close(index);
            return false;
        }
    });
};

//打开全屏的弹出框
commonJs.openFullDialog = function (url) {
    index = layer.open({
        type: 2,
        title: false,
        closeBtn: 0,
        maxmin: false,
        shadeClose: false,
        area: ['90%', '90%'],
        scrollbar: false,
        content: url
    });
    layer.full(index);
}

//关闭当前弹出框layer
commonJs.closeLayer = function () {
    var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
    parent.layer.close(index);
}

//省略显示文本
commonJs.ellipsisDisplay = function (content, length) {
    if (content == null || content == '') {
        return '';
    }
    length = length || 20;
    if (content.length <= length) {
        return content;
    }
    return content.substring(0, length) + '...';
}

//返回上一页
commonJs.historyBack = function (e) {
    e.preventDefault();
    e.stopPropagation();
    history.back();
}

//通过出生日期计算年龄
commonJs.calculateAge = function (birthdate) {
    if (birthdate == null || birthdate == '') {
        return;
    }
    birthdate = commonJs.formateDate(new Date(birthdate.replace(/-/g, "/")));

    var age;
    var strBirthdayArr = birthdate.split("-");
    var birthYear = strBirthdayArr[0];
    var birthMonth = strBirthdayArr[1];
    var birthDay = strBirthdayArr[2];

    var now = new Date();
    var nowYear = now.getFullYear();
    var nowMonth = now.getMonth() + 1;
    var nowDay = now.getDate();
    if (nowYear == birthYear) {
        age = 0;//同年 则为0岁
    } else {
        var ageDiff = nowYear - birthYear; //年之差
        if (ageDiff > 0) {
            if (nowMonth == birthMonth) {
                var dayDiff = nowDay - birthDay;//日之差
                if (dayDiff < 0) {
                    age = ageDiff - 1;
                } else {
                    age = ageDiff;
                }
            } else {
                var monthDiff = nowMonth - birthMonth;//月之差
                if (monthDiff < 0) {
                    age = ageDiff - 1;
                } else {
                    age = ageDiff;
                }
            }
        } else {
            age = -1;//返回-1 表示出生日期输入错误 晚于今天
        }
    }
    return age;//返回周岁年龄
}

//格式化日期对象，默认格式：yyyy-MM-dd
commonJs.formateDate = function (date, fmt) {
    if (date == null || date == '') {
        return "";
    }
    if (!(date instanceof Date)) {
        return;
    }
    fmt = fmt || 'yyyy-MM-dd';
    var o = {
        'M+': date.getMonth() + 1, //月份
        'd+': date.getDate(), //日
        'h+': date.getHours(), //小时
        'm+': date.getMinutes(), //分
        's+': date.getSeconds(), //秒
        'q+': Math.floor((date.getMonth() + 3) / 3), //季度
        'S': date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

//获取指定位数的随机数
commonJs.getSerialNumber = function (number) {
    number = number || 6;
    var serialNumber = "";
    for (var i = 0; i < number; i++) {
        serialNumber += Math.floor(Math.random() * 10);
    }
    return serialNumber;
}

//上传图片到服务器并且把图片插入到富文本编辑框
commonJs.onImageUpload = function (target, ctx, files) {
    if (target == null || target == '') {
        return;
    }
    if (files == null || files.length < 0) {
        return;
    }
    for (var i = 0; i < files.length; i++) {
        var data = new FormData();
        data.append("file", files[i]);
        $.ajax({
            data: data,
            type: "POST",
            url: ctx + "/common/sysFile/upload", //后台文件上传接口，返回的是图片上传后的路径，http格式
            cache: false,
            contentType: false,
            processData: false,
            success: function (url) {
                $("#" + target).summernote('insertImage', ctx + url.fileUrl);
            }
        });
    }
}

//回车键查询事件
commonJs.enterEvent = function (target, callback) {
    callback = callback || function () {
    };
    $(target).keydown(function (e) {
        // 兼容FF和IE和Opera
        var event = e || window.event;
        var keyCode = event.keyCode || event.which;
        if (keyCode === 13) {
            callback();
        }
    });
}

//初始化layui的table
commonJs.tableTextNone = '暂无数据！';
commonJs.tableRender = function (table, cols, url, height, data, target, callback) {
    data = data || {};
    height = height || '';
    target = target || 'LAY-table';
    callback = callback || function () {
    };
    if (height == '') {
        var clientHeight = Math.floor(document.body.clientHeight / 4);
        height = 'full-' + clientHeight;
    }
    table.render({
        elem: "#" + target,
        url: url,
        cols: [cols],
        height: height,
        request: {
            pageName: 'pageNumber',
            limitName: 'pageSize'
        },
        page: {
            limit: 20,
            limits: [20, 40, 60, 80]
        },
        where: data,
        cellMinWidth: 60,
        text: {
            'none': commonJs.tableTextNone
        },
        done: function (res, curr, count) {
            callback(res, curr, count);
        }
    });
};

//初始化layui的table的tool操作
commonJs.tableTool = function (table, prefix, data) {
    data = data || {};
    table.on("tool(LAY-table)", function (e) {
        if ("del" === e.event) {
            commonJs.openConfirm('确定删除吗？', function () {
                commonJs.openAjax(prefix + "/remove", {"id": e.data.id}, function (result) {
                    if (result.code == 0) {
                        commonJs.openMsg('success', '删除成功！', function () {
                            table.reload('LAY-table'); //数据刷新
                        });
                    } else {
                        commonJs.openMsg('error', result.msg);
                    }
                });
            });
        } else if ("edit" === e.event) {
            commonJs.openDialog('编辑', prefix + '/edit/' + e.data.id, data, [], function (index, layero) {
                var iframeWindow = window['layui-layer-iframe' + index]
                    , submitID = 'LAY-operate-submit'
                    , submit = layero.find('iframe').contents().find('#' + submitID);

                //监听提交
                iframeWindow.layui.form.on('submit(' + submitID + ')', function (data) {
                    commonJs.openAjax(prefix + "/update", data, function (result) {
                        if (result.code == 0) {
                            commonJs.openMsg('success', '编辑成功！', function () {
                                table.reload('LAY-table'); //数据刷新
                                layer.close(index);        //关闭弹层
                            });
                        } else {
                            commonJs.openMsg('error', result.msg);
                        }
                    });
                });
                submit.trigger('click');
            });
        }
    });
}

// 重写校验layer form verify
commonJs.form = {
    config: {
        verify: {
            required: [/[\S]+/, "必填项不能为空！"],
            phone: [/(^1\d{10})$/, "请输入正确的手机号！"],
            email: [/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, "邮箱格式不正确！"],
            url: [/(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确！"],
            number: function (e) {
                if (!e || isNaN(e)) return "只能填写数字！"
            },
            date: [/^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/, "日期格式不正确！"],
            identity: [/(^\d{15}$)|(^\d{17}(x|X|\d)$)/, "请输入正确的身份证号！"]
        }
    },
    verify: {
        required: function (value) {
            if (/[\S]+/.test(value)) return "";
            return "必填项不能为空！";
        },
        phone: function (value) {
            if (value == '' || /(^1\d{10})$/.test(value)) return "";
            return "请输入正确的手机号！";
        },
        email: function (value) {
            if (value == '' || /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value)) return "";
            return "邮箱格式不正确！";
        },
        url: function (value) {
            if (value == '' || /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/.test(value)) return "";
            return "链接格式不正确！";
        },
        number: function (value) {
            if (value == '') return "";
            if (!value || isNaN(value)) return "只能填写数字！";
            return "";
        },
        date: function (value) {
            if (value == '' || /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/.test(value)) return "";
            return "日期格式不正确！";
        },
        identity: function (value) {
            if (value == '' || /(^\d{15}$)|(^\d{17}(x|X|\d)$)/.test(value)) return "";
            return "请输入正确的身份证号！";
        }
    }
};

//获取选中树节点的Ids
commonJs.getTreeCheckedIds = function (checkData) {
    var ids = '';
    $(checkData).each(function (index, item) {
        ids = ids + item.id + ',';
        if (null != item.children && item.children.length > 0) {
            ids = ids + commonJs.getTreeCheckedIds(item.children);
        }
    });
    return ids;
}

//layuiadmin打开新的页签
commonJs.openTabsPage = function (url, title) {
    if (top.layui.index) {
        top.layui.index.openTabsPage(url, title)
    } else {
        window.open(url);
    }
}